import React, { useState, useEffect } from 'react';
import { Layout as AntLayout, Menu, Button, Avatar, Dropdown, Space } from 'antd';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  DashboardOutlined,
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
} from '@ant-design/icons';
import { RootState } from '../store';
import { logout } from '@/store/slices/authSlice';
import SystemSettings from './SystemSettings';
import './Layout.scss';
import * as Icons from '@ant-design/icons';

const { Header, Sider, Content } = AntLayout;

// 主布局组件
const Layout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(() => {
    const stored = localStorage.getItem('sider-collapsed');
    return stored ? stored === 'true' : false;
  });
  const [theme, setTheme] = useState<'light' | 'dark'>('dark');
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();
  const { t } = useTranslation();
  const { userInfo, menus } = useSelector((state: RootState) => state.auth);

  // 动态构建菜单项，兼容 icon 字符串
  const buildMenuItems = (menuList: any[]): any[] =>
    menuList.map(menu => {
      let iconNode = undefined;
      if (menu.icon && typeof menu.icon === 'string' && (Icons as any)[menu.icon]) {
        const IconComp = (Icons as any)[menu.icon];
        iconNode = <IconComp />;
      }
      return {
        key: menu.path,
        icon: iconNode,
        label: menu.name,
        children: menu.children && menu.children.length > 0 ? buildMenuItems(menu.children) : undefined,
      };
    });

  const menuItems = menus && menus.length > 0 ? buildMenuItems(menus) : [];

  // 处理菜单点击
  const handleMenuClick = ({ key }: { key: string }) => {
    navigate(key);
  };

  // 处理登出
  const handleLogout = () => {
    dispatch(logout());
    navigate('/login');
  };

  // 用户菜单项
  const userMenuItems = [
    {
      key: 'profile',
      label: '个人资料',
      icon: <UserOutlined />,
    },
    {
      key: 'settings',
      label: '设置',
      icon: <SettingOutlined />,
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ];

  // 主题切换处理
  const handleThemeChange = (newTheme: 'light' | 'dark') => {
    setTheme(newTheme);
    // 这里可以添加主题切换的逻辑
    document.body.setAttribute('data-theme', newTheme);
  };

  // 递归查找当前path的所有父级key
  const findOpenKeys = (menuList: any[], pathname: string, parents: string[] = []): string[] => {
    for (const menu of menuList) {
      if (menu.path === pathname) {
        return parents;
      }
      if (menu.children) {
        const found = findOpenKeys(menu.children, pathname, [...parents, menu.path]);
        if (found.length) return found;
      }
    }
    return [];
  };

  const [openKeys, setOpenKeys] = useState<string[]>([]);

  useEffect(() => {
    if (menus && menus.length > 0) {
      const keys = findOpenKeys(menus, location.pathname);
      setOpenKeys(keys);
    }
  }, [location.pathname, menus]);

  // 侧边栏折叠切换
  const handleCollapse = () => {
    setCollapsed(prev => {
      localStorage.setItem('sider-collapsed', String(!prev));
      return !prev;
    });
  };

  return (
    <AntLayout className={`app-layout ${theme}`}>
      {/* 侧边栏 */}
      <Sider 
        trigger={null} 
        collapsible 
        collapsed={collapsed}
        className="app-sider"
      >
        {/* Logo 区域 */}
        <div className="logo">
          {!collapsed && <h1>Admin</h1>}
        </div>
        
        {/* 导航菜单 */}
        <Menu
          theme={theme}
          mode="inline"
          selectedKeys={[location.pathname]}
          openKeys={openKeys}
          onOpenChange={setOpenKeys}
          items={menuItems}
          onClick={handleMenuClick}
        />
      </Sider>

      <AntLayout>
        {/* 顶部导航栏 */}
        <Header className="app-header">
          <div className="header-left">
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={handleCollapse}
              className="trigger-button"
            />
          </div>

          <div className="header-right">
            <SystemSettings 
              theme={theme} 
              onThemeChange={handleThemeChange} 
            />
            
            <Dropdown
              menu={{ items: userMenuItems }}
              placement="bottomRight"
              trigger={['click']}
            >
              <Space className="user-info">
                <Avatar icon={<UserOutlined />} />
                {!collapsed && (
                  <span className="username">{userInfo?.username}</span>
                )}
              </Space>
            </Dropdown>
          </div>
        </Header>

        {/* 主内容区域 */}
        <Content className="app-content">
          <div className="content-wrapper">
            <Outlet />
          </div>
        </Content>
      </AntLayout>
    </AntLayout>
  );
};

export default Layout; 